const app = Vue.createApp({
    // 定义变量
    data() {
        return {
            nav_tap_list: [{
                index: 0,
                hash: "#message",
                name: "消息",
                header: "Message",
                icon: "mui-icon-chatbubble"
            }, {
                index: 1,
                hash: "#contacts",
                name: "联系人",
                header: "Contacts",
                icon: "mui-icon-paperplane"
            }, {
                index: 2,
                hash: "#world",
                name: "world",
                header: "World",
                icon: "mui-icon-flag"
            }, {
                index: 3,
                hash: "#owner",
                name: "我",
                header: "Owner",
                icon: "mui-icon-person"
            }],
            cur_index: 0,
            win: "main",

            owner_id: 0,
            other_id: 0,
            msg_type: 0,
            token: "",
            owner_info: null,
            other_info: null,
            session_list: null,
            ws: null,
            friend_request: null,
            contacts: null,
        }
    },

    // 函数定义
    methods: {
        init: function() {
            this.initNav();
            this.getOwnerInfo();
            this.getSessionList();
            // this.initWs();
        },
        initNav: function() {
            var hash = window.location.hash;
            var index = 0;
            for (var i in this.nav_tap_list) {
                if (hash === this.nav_tap_list[i].hash) {
                    index = this.nav_tap_list[i].index;
                    break;
                }
            }
            this.navSwitch(index);
        },
        navSwitch: function(i) {
            this.cur_index = i;
            window.location.href = this.nav_tap_list[i].hash;
        },
        navTap: function(i) {
            console.log(i);
            this.navSwitch(i);
        },
        initWs: function() {
            // 初始化websocket
            if (this.ws) return;

            this.ws = new WebSocket("ws://127.0.0.1:8080/ws?uid=" + this.owner_id);
            this.ws.onopen = function(evt) {
                this.ws.send("hello");
            }.bind(this);
            this.ws.onmessage = function(evt) {
                console.log(evt.data);
                var msg = JSON.parse(evt.data);
                // 聊天窗口已经打开，才会显示消息
                if (this.win === "chat") {
                    this.showWsMsg(msg);
                }
                // 将消存入local storage，并更新会话
                if (msg.owner_id == this.owner_id) { //自己发的消息
                    this.writeMsg(msg.other_id, msg);
                    this.updateSession(msg.other_id, msg);
                } else { //别人发来的消息
                    this.writeMsg(msg.owner_id, msg);
                    this.updateSession(msg.owner_id, msg);
                }

                // 如果收到的消息不属于当前打开的会话窗口，则未读消息+1
                if (msg.owner_id != this.other_id && msg.owner_id != this.owner_id) {
                    for (let i = 0; i < this.session_list.length; i++) {
                        if (this.session_list[i].other_id == msg.owner_id) {
                            this.session_list[i].unread_msg_count += 1;
                        }
                    }
                }

            }.bind(this);
            this.ws.onclose = function(evt) {
                alert("close");
            };
            this.ws.onerror = function(evt) {
                alert("error");
            }
        },
        getOwnerInfo: function() {
            // 获取owner信息
            this.token = localStorage.getItem("token");
            this.owner_info = JSON.parse(localStorage.getItem("userinfo"));
            this.owner_id = this.owner_info.id;
        },
        getSessionList: function() {
            // 获取会话列表
            var that = this;
            $.ajax({
                url: "/info/session",
                type: "get",
                data: {
                    owner_id: that.owner_info.id
                },
                headers: {
                    "token": that.token
                },
                success: function(res) {
                    console.log(res)
                    if (res.code !== 0) {
                        return mui.toast(res.msg);
                    }
                    that.session_list = res.data;
                },
                error: function(res) {
                    console.log(res)
                }
            })
        },
        startChat: function(item) {
            // 打开聊天窗口，从会话信箱中载入消息
            // 如果存在离线消息，则从服务端拉取，并存入会话信箱中
            console.log(item)

            this.win = "chat";
            this.msg_type = item.msg_type;
            this.other_info = item;
            this.other_id = item.other_id;

            // 获取离线消息，并存入会话信箱
            if (item.unread_msg_count > 0) {
                this.getOfflineMsg();
            }

            // 获取会话信箱中的消息并显示
            var msg_list = this.readMsg(item.other_id);
            console.log(msg_list);
            this.showManyMsg(msg_list);
            console.log(msg_list);

        },
        endChat: function() {
            // 关闭聊天窗口
            this.win = 'main';
            this.other_id = 0;
        },
        getOfflineMsg: function() {
            // 获取离线消息，并存入会话信箱
            var that = this;
            $.ajax({
                url: "/info/getoffmsg",
                type: "get",
                data: {
                    owner_id: that.owner_id,
                    other_id: that.other_id
                },
                headers: {
                    "token": that.token
                },
                success: function(res) {
                    console.log("获取离线消息");
                    console.log(res)
                    if (res.code !== 0) {
                        return mui.toast(res.msg);
                    }
                    // 将离线消息存入会话信箱
                    if (res.data) {
                        that.writeMsg(that.other_id, res.data);
                    }

                    // 未读消息清零
                    for (let i = 0; i < that.session_list.length; i++) {
                        if (that.session_list[i].other_id == that.other_id) {
                            that.session_list[i].unread_msg_count = 0;
                        }
                    }
                },
                error: function(res) {
                    console.log(res);
                }
            })
        },
        getFriendReq: function() {
            var that = this;
            $.ajax({
                url: "/info/friendrequest",
                type: "GET",
                headers: {
                    "token": that.token
                },
                data: {
                    "owner_id": that.owner_id
                },
                success: function(res) {
                    console.log(res);
                    if (res.code !== 0) {
                        return mui.toast(res.msg);
                    }
                    that.friend_request = res.data;
                },
                error: function(res) {
                    console.log(res);
                }
            })
        },
        agreeFriendReq(uid) {
            var that = this;
            $.ajax({
                url: "/info/friendrequest",
                type: "PUT",
                headers: {
                    "token": that.token
                },
                data: {
                    "owner_id": uid,
                    "other_id": that.owner_id
                },
                success: function(res) {
                    console.log(res)
                    mui.toast(res.msg)
                    if (res.code !== 0) {
                        return;
                    }
                    that.getFriendReq()
                    that.getSessionList();
                },
                error: function(res) {
                    console.log(res)
                }
            })
        },
        getContacts: function() {
            var that = this;
            $.ajax({
                url: "/info/contacts",
                type: "GET",
                headers: {
                    "token": that.token
                },
                data: {
                    "owner_id": that.owner_id
                },
                success: function(res) {
                    console.log(res)
                    mui.toast(res.msg)
                    if (res.code !== 0) {
                        return;
                    }
                    that.contacts = res.data;
                },
                error: function(res) {
                    console.log(res)
                }
            })
        },
        selectImg: function(e) {
            // 发送图片，还未实现发送给对端
            if (!e.target.files || !e.target.files[0]) {
                return;
            }
            var reader = new FileReader();
            reader.readAsDataURL(e.target.files[0]); // 异步读取选择的第一张图片
            reader.onload = function(evt) { // 读取到图片后执行
                var images = evt.target.result;
                this.showOneMsg(images, "img");
            };
            $(e.target).val(""); // 解决连续上传相同图片不能触发change的问题
        },
        sendMsg: function() {
            var textContent = $(".div-textarea").html().replace(/[\n\r]/g, '<br>');
            if (textContent != "") {
                // 显示message
                // this.showOneMsg(textContent, "text");
                // 发送消息到服务器
                this.sendWsMsg(textContent);
                //发送后清空输入框
                $(".div-textarea").html("");
            }
        },
        sendWsMsg: function(content, type = "text") {
            // 向对端发送消息
            var msg = {
                msg_id: 0, // 消息达到服务器后，会生成全局唯一msg_id
                owner_id: this.owner_id,
                other_id: this.other_info.other_id,
                msg_type: 2,
                media: 1,
                content: content,
                pic: "",
                url: "",
                desc: "",
                create_time: 0 // 消息达到服务器后，获取服务器时间戳，解决多个客户端时钟不一致的问题
            }

            this.ws.send(JSON.stringify(msg));
            // 将消存入local storage
            // this.writeMsg(msg.other_id, msg);
        },
        showWsMsg: function(msg) {
            var is_owner = true;
            if (this.owner_id != msg.owner_id) {
                is_owner = false;
            }

            switch (msg.media) { // 消息展示形式
                case 1:
                    this.showOneMsg(msg.content, "text", is_owner);
                    break;
                case 2:
                    this.showOneMsg(msg.url, "img", is_owner);
                    break;
            }
        },

        showOneMsg: function(msg, type = "text", is_owner = true) {
            // 显示一条消息
            var content = "";
            switch (type) {
                case "text":
                    content = msg;
                    break;
                case "img":
                    content = `<img src="${msg}">`;
                    break;
            }
            var data = [{
                content,
                is_owner
            }];
            var elem = this.getElem(data);

            $(".chatBox-content-demo").append(elem);
            //聊天框默认最底部
            $(document).ready(function() {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
        },

        showManyMsg: function(data) {
            // 显示多条消息，用在打开聊天窗口时
            var elems = [];
            for (let i = 0; i < data.length; i++) {
                var content = "";
                switch (data[i].media) {
                    case 1:
                        content = data[i].content;
                        break;
                    case 2:
                        content = `<img src="${data[i].url}">`;
                        break;
                }
                var is_owner = this.owner_id == data[i].owner_id ? true : false;
                var elem = {
                    content,
                    is_owner
                };
                elems.push(elem);
            }

            var lis = this.getElem(elems);

            $(".chatBox-content-demo").html('').append(lis);
            //聊天框默认最底部
            $(document).ready(function() {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
        },

        getElem: function(data) {
            if (!data) return '';
            var elem = '';
            for (let i = 0; i < data.length; i++) {
                if (data[i].is_owner) {
                    elem += `
                    <div class="clearfloat">
                        <div class="author-name">
                            <small class="chat-date">2021-05-01 14:26:58</small> 
                        </div>
                        <div class="right">
                            <div class="chat-message">
                                ${data[i].content}
                            </div>
                            <div class="chat-avatars">
                                <img src="${this.owner_info.avator}" alt="头像"/>
                            </div>
                        </div>
                    </div>`;
                } else {
                    elem += `
                    <div class="clearfloat">
                        <div class="author-name">
                            <small class="chat-date">2017-12-02 14:26:58</small>
                        </div>
                        <div class="left">
                            <div class="chat-avatars">
                                <img src="${this.other_info.avator}" alt="头像" />
                            </div>
                            <div class="chat-message">
                                ${data[i].content}
                            </div>
                        </div>
                    </div>
                    `;
                }
            }

            return elem;
        },
        writeMsg: function(key, msg) {
            // 将消息存储在本地，msg可为消息数组或消息
            var data = localStorage.getItem(key);
            var msg_list = [];
            if (data) {
                msg_list = JSON.parse(data);
            }

            if (Array.isArray(msg)) {
                for (let i = 0; i < msg.length; i++) {
                    msg_list.push(msg[i]);
                }
            } else {
                msg_list.push(msg);
            }

            localStorage.setItem(key, JSON.stringify(msg_list));
        },
        readMsg: function(key, count = -1) {
            // 从本地读取消息
            // count为读取信息数量，count=-1时，读取全部的信息
            var data = localStorage.getItem(key)
            if (!data) {
                return [];
            }

            if (count === -1) {
                return JSON.parse(data);
            }

            return [];
        },
        updateSession: function(key, msg) {
            // 收到消息时，更新会话信息
            for (let i = 0; i < this.session_list.length; i++) {
                if (key == this.session_list[i].other_id) {
                    this.session_list[i].last_msg = msg;
                }
            }
        }


    },

    created: function() {
        this.init();
        console.log(this.token)
    },
    // 计算属性
    computed: {
        UnreadMsgNum() {
            // 所有未读消息数量
            var num = 0;
            if (this.session_list) {
                for (let i = 0; i < this.session_list.length; i++) {
                    num += this.session_list[i].unread_msg_count;
                }
            }
            return num;
        }
    },

    mounted: function() {
        this.initWs();
    },

    // 监听变量
    watch: {

    },

})

app.mount('#app')